package com.toutiao.time

import scala.math.sqrt

object SimpleFactory {

  def norm(vs:Map[String,Double]) = {
	if (vs.size > 0){
	    var s = vs.map(x => x._2*x._2).reduce(_+_)
	    s = sqrt(s)
	    vs.map(x => {
	      (x._1,x._2/s)
	    })
	 }
	 else {
	    vs
	 }
  }
  
  def cos(m1:Map[String,Double], s1:Double, m2:Map[String,Double], s2:Double):Double = {
    var s = 0.0
    for ( (k,v) <- m1){
      s += v*m2.getOrElse(k,0.0)
    }
    s/(s1*s2)
  }
  
  def merge(m1:Map[String,Double],n1:Int,m2:Map[String,Double],n2:Int) = {
    val n = n1+n2
    var z = m1
    for ( (k,v) <- m2){
      var x = v*n2+z.getOrElse(k,0.0)*n1
      z += k->x/n
    }
    val N = 30
    var s = z.map(x => x._2*x._2).reduce(_+_)
    if (z.size < N){
      s = N*s/z.size
    }
    s = sqrt(s)
    z.map( x => {
      (x._1,x._2/s)
    })
  }
  
  def cut(vs:Map[String,Double],size:Int=60) = {
    if (vs.size <= size){
      vs
    }
    else {
      val us = vs.toArray.sortBy(-_._2)
      val ss = us(size)._2
      val ns = vs.filter(_._2 > ss)
      val s = ns.map(x => x._2*x._2).reduce(_+_)
      ns.map(x => {(x._1,x._2/s)})
    }
  } 
  
}